import {useOrganStore} from "@/store/flowable";
import http from "@/utils/request"
import config from "@/config";
import caches from "@/utils/cache";

// 数据缓存
let cache = {
    loaded: false,
};

/**
 * 获取部门
 * @param {*} params
 * @returns
 */
export async function listDepts(params) {
	return await http.post(config.API_URL+"/console/organization/listData",params,{});
}

/**
 * 获取角色
 * @param {*} params
 * @returns
 */
export async function listRoles(params) {
	return await http.post(config.API_URL+"/console/role/listData",params,{});
}

/**
 * 获取职员
 * @param {*} params
 * @returns
 */
export async function listUsers(params) {
	return await http.post(config.API_URL+"/console/operator/listData",params,{});
}

export async function getUserDetail(params) {
	return await http.post(config.API_URL+"/console/operator/findById/"+params.id,{},{});
}

export async function getLoginUserDetail(params) {
	return await http.post(config.API_URL+"/console/operator/findById/"+params.id,{},{});
}

export async function loadOrgan() {
	if (!cache.loaded) {
		const {setDepts, setRoles, setUsers} = useOrganStore();
		let deptData = await caches.dic.options("SysOrganization", true);
		if (deptData) {
			let newOrgData = [];
			deptData.forEach((item) => {
				let user = {
					id: '',
					name: ''
				}
				if (item.label) {
					user.name = item.label;
				}
				if (item.value) {
					user.id = item.value;
				}
				newOrgData.push(user);
			});
			setDepts(newOrgData);
		}
		let roleData = await caches.dic.options("SysRole", true);
		if (roleData) {
			let newRoleData = [];
			roleData.forEach((item) => {
				let user = {
					id: '',
					name: ''
				}
				if (item.label) {
					user.name = item.label;
				}
				if (item.value) {
					user.id = item.value;
				}
				if (item.id != "A0F62F77-EAA7-400C-B415-7920EC6338BF") {
					newRoleData.push(user);
				}
			});
			setRoles(newRoleData);
		}
		let userData = await caches.dic.options("SysUser", true);
		let newUserData = [];
		userData.forEach((item) => {
			if(item.t){
				let user = {
					id: '',
					name: ''
				}
				if (item.label) {
					user.name = item.label;
				}
				if (item.value) {
					user.id = item.value;
				}
				newUserData.push(user);
			}
		});
		setUsers(newUserData);
		cache.loaded = true;
	}
}

export default { loadOrgan, listDepts, listRoles, listUsers, getUserDetail, getLoginUserDetail };
